<?php

namespace app\manystore\controller;

use app\common\controller\ManystoreBase;
use think\Db;
use addons\epay\library\Service;

/**
 * 
 *
 * @icon fa fa-circle-o
 */
class Auditorder extends ManystoreBase
{

    /**
     * Order模型對象
     * @var \app\manystore\model\Order
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\manystore\model\Order;
        $this->view->assign("orderStatusList", $this->model->getOrderStatusList());
        $this->view->assign("orderAttributesList", $this->model->getOrderAttributesList());
        $this->view->assign("orderTypeList", $this->model->getOrderTypeList());
        $this->view->assign("payStatusList", $this->model->getPayStatusList());
        $this->view->assign("freightStatusList", $this->model->getFreightStatusList());
        $this->view->assign("receiptStatusList", $this->model->getReceiptStatusList());
        $this->view->assign("refundStatusList", $this->model->getRefundStatusList());
        $this->view->assign("commentStatusList", $this->model->getCommentStatusList());
        $this->view->assign("regionTypeList", $this->model->getRegionTypeList());
    }

    public function import()
    {
        parent::import();
    }

    /**
     * 默認生成的控製器所繼承的父類中有index/add/edit/del/multi五個基礎方法、destroy/restore/recyclebin三個回收站方法
     * 因此在當前控製器中可不用編寫增刪改查的代碼,除非需要自己控製這部分邏輯
     * 需要將application/admin/library/traits/Backend.php中對應的方法復製到當前控製器,然後進行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //當前是否為關聯查詢
        $this->relationSearch = true;
        //設置過濾方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果發送的來源是Selectpage，則轉發到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    ->alias('order')
                    ->field('order.*,r.refund_reason,r.refund_content,r.createtime as r_createtime,r.return_reason')
                    ->join('order_refund r','r.id = order.refund_id')
                    ->where(['order.refund_status'=>['neq','10']])
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);
            foreach ($list as $row) {
                $user = db('user')->where(['id'=>$row->user_id])->find();
                $row->nickname = $user['nickname'];
                $row->avatar = $user['avatar'];
                $goods = db('order_goods')->where(['order_id'=>$row->id])->order('id asc')->find();
                $row['goods_images'] = explode(',', $goods['images'])[0];
                $row['goods_name'] = $goods['goods_name'];
                $row['name'] = $row['name'].':'.$row['mobile'];
                // $row['avatar'] = $row['user']['avatar'];
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }

        $this->assignconfig("order_edit", $this->auth->check("auditorder/edit"));
        $this->assignconfig("order_audit", $this->auth->check("auditorder/audit"));
        return $this->view->fetch();
    }

    /**
     * 刪除
     */
    public function cancel($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }

        $time = time();
        $ids = $ids ? $ids : $this->request->post("ids");
        if ($ids) {
            $pk = $this->model->getPk();
            if($this->shopIdAutoCondition){
                $this->model->where(array('shop_id'=>SHOP_ID));
            }
            $list = $this->model->where($pk, 'in', $ids)->select();

            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $k => $v) {
                    $count += $v->save(['order_status'=>'50','canceltime'=>$time]);
                }
                Db::commit();
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }

    /**
     * 編輯
     */
    public function edit($ids = null)
    {
        if($this->shopIdAutoCondition){
            $this->model->where(array('shop_id'=>SHOP_ID));
        }
        $row = $this->model->where(array('id'=>$ids))->find();
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        $row['goods'] = $goods = db('order_goods')->where(['order_id'=>['in',$row['id']]])->select();
        $row['total_num'] = db('order_goods')->where(['order_id'=>['in',$row['id']]])->sum('total_num');
        $user = db('user')->field('*')->where(['id'=>$row['user_id']])->find();
        $order_refund = db('order_refund')->where(['id'=>$row['refund_id']])->find();

        $this->view->assign("order_refund", $order_refund);
        $this->view->assign("user", $user);
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                // 發貨
                $expressquery = db('expressquery')->where(['id'=>$params['express']])->find();
                $params['express'] = $expressquery['express'];
                $params['expressname'] = $expressquery['name'];
                $params['order_status'] = '30';
                $params['freight_status'] = '20';
                $params['freighttime'] = time();
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型驗證
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 編輯
     */
    public function audit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ( $row['refund_status'] !== '20' ) {
            $this->error('狀態錯誤');
        }
        $adminIds = $this->getDataLimitAdminIds();

        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ( $params['refund_status'] == '40' && !$params['return_reason'] ) {
                $this->error('請填寫拒絕原因');
            }
            if ($params) {
                $time = time();
                $refund_arr = [];
                $refund_arr['refund_status'] = $params['refund_status'];
                $refund_arr['return_reason'] = $params['return_reason'];
                $refund_arr['audittime'] = $time;
                unset($params['return_reason']);

                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型驗證
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    // 同意退款
                    if ( $params['refund_status'] == '30' ) {
                        $params['order_status'] = '50';
                        $params['canceltime'] = $time;
                    }else{
                        sendMessage(1,'您的訂單'.$row['order_no'].'退款申請不通過','',$row['user_id'],3,$row['id']);
                    }
                        $result = $row->allowField(true)->save($params);

                    if ( $params['refund_status'] == '30'  && $result ) {
                        $total_fee = db('order')->where(['parent_order_no'=>$row['parent_order_no']])->sum('pay_price');
                        // 退款
                        $Service = new Service;
                        $pay = $Service->createPay('wechat',[]);
                        $orderDate = [];
                        $orderDate['transaction_id'] = $row['transaction_id'];
                        $orderDate['out_trade_no'] = $row['parent_order_no'];
                        $orderDate['out_refund_no'] = $row['order_no'];

                        $orderDate['total_fee'] = $total_fee*100;
                        $orderDate['refund_fee'] = $row['pay_price']*100;
                        $orderDate['refund_desc'] = '申請退款';
                        $orderDate['notify_url'] = '';
                        
                        $result = $pay->refund($orderDate);
                        if($result['return_code'] == 'FAIL' || $result['result_code'] == 'FAIL'){
                            \Think\Log::record('退款失敗,訂單號為'.$order_id,'notice');
                            \Think\Log::record('退款失敗,內容為:'.print_r($result,1),'notice');
                            // 回滾事務
                            Db::rollback();
                            $this->error('退款失敗');
                        }else{
                            sendMessage(1,'您的訂單'.$row['order_no'].'退款申請已通過','',$row['user_id'],3,$row['id']); 
                        }
                    }

                    db('order_refund')->where(['order_id'=>$row->id])->update($refund_arr);
                    refund($row->id);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (\Exception $e) {
                    Db::rollback();
                    \Think\Log::record('退款失敗,錯誤為'.$e->getMessage(),'notice');
                    $this->error('退款失敗');
                    // $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }
}
